<?php

declare(strict_types=1);

namespace App\Middleware;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\HttpMessage\Stream\SwooleStream;
use App\Exception\ValidateException;
use Hyperf\HttpServer\Router\Dispatched;



class ActionMiddleware implements MiddlewareInterface
{
	
	/**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var HttpResponse
     */
    protected $response;
	

    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
    }
	
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
		if($this->request->getAttribute(Dispatched::class)->isFound()){
			$route = $this->request->getAttribute(Dispatched::class)->handler->callback;
			if($route[0]){
				if($route[1] == 'beforeAction'){
					return $this->response->withStatus(404)->withBody(new SwooleStream(file_get_contents(BASE_PATH. '/public/404.html')));
				}
				
				$controller = container()->get($route[0]);
				if (method_exists($controller, 'beforeAction')) {
					$response = call_user_func([$controller, 'beforeAction'], $request);
					if($response) {
						return $this->response->withHeader('Server', 'Hyperf')->withStatus(200)->withBody(new SwooleStream($response));
					}
				}
				return $handler->handle($request);
			}
		}
		return $handler->handle($request);
    }
    
} 